package com.fy.proj5_permission_transaction_cache.service.impl;

import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.service.PageVisitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 页面访问统计服务实现类
 */
@Service
public class PageVisitServiceImpl implements PageVisitService {

    private static final Logger logger = LoggerFactory.getLogger(PageVisitServiceImpl.class);
    
    @Autowired
    private CacheService cacheService;
    
    // Redis键前缀
    private static final String PAGE_VISIT_PREFIX = "page:visit:";
    private static final String IP_VISIT_PREFIX = "page:ip:visit:";
    
    // 默认过期时间：30天
    private static final long DEFAULT_EXPIRATION = 30;
    private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.DAYS;
    
    /**
     * 生成页面访问的Redis键
     */
    private String getPageVisitKey(String pageName) {
        return PAGE_VISIT_PREFIX + pageName;
    }
    
    /**
     * 生成IP访问的Redis键
     */
    private String getIpVisitKey(String pageName, String ip) {
        return IP_VISIT_PREFIX + pageName + ":" + ip;
    }
    
    @Override
    public long recordVisit(String pageName) {
        if (pageName == null || pageName.trim().isEmpty()) {
            logger.warn("Page name cannot be null or empty");
            return 0;
        }
        
        try {
            String key = getPageVisitKey(pageName);
            long count = cacheService.increment(key);
            
            // 设置过期时间（如果键不存在才设置，避免频繁更新过期时间）
            if (count == 1) {
                cacheService.expire(key, DEFAULT_EXPIRATION, DEFAULT_TIME_UNIT);
            }
            
            logger.debug("Page visited: {}, count: {}", pageName, count);
            return count;
        } catch (Exception e) {
            logger.error("Failed to record page visit for: {}", pageName, e);
            return 0;
        }
    }
    
    @Override
    public long getVisitCount(String pageName) {
        if (pageName == null || pageName.trim().isEmpty()) {
            logger.warn("Page name cannot be null or empty");
            return 0;
        }
        
        try {
            String key = getPageVisitKey(pageName);
            Object value = cacheService.get(key);
            if (value != null) {
                return Long.parseLong(value.toString());
            }
            return 0;
        } catch (Exception e) {
            logger.error("Failed to get visit count for: {}", pageName, e);
            return 0;
        }
    }
    
    @Override
    public boolean resetVisitCount(String pageName) {
        if (pageName == null || pageName.trim().isEmpty()) {
            logger.warn("Page name cannot be null or empty");
            return false;
        }
        
        try {
            String key = getPageVisitKey(pageName);
            boolean result = cacheService.delete(key);
            logger.info("Visit count reset for page: {}, result: {}", pageName, result);
            return result;
        } catch (Exception e) {
            logger.error("Failed to reset visit count for: {}", pageName, e);
            return false;
        }
    }
    
    @Override
    public long recordIpVisit(String pageName, String ip) {
        if (pageName == null || pageName.trim().isEmpty() || ip == null || ip.trim().isEmpty()) {
            logger.warn("Page name or IP cannot be null or empty");
            return 0;
        }
        
        try {
            String key = getIpVisitKey(pageName, ip);
            long count = cacheService.increment(key);
            
            // 设置过期时间（如果键不存在才设置）
            if (count == 1) {
                cacheService.expire(key, DEFAULT_EXPIRATION, DEFAULT_TIME_UNIT);
            }
            
            logger.debug("IP visited page: page={}, ip={}, count={}", pageName, ip, count);
            return count;
        } catch (Exception e) {
            logger.error("Failed to record IP visit: page={}, ip={}", pageName, ip, e);
            return 0;
        }
    }
    
    @Override
    public long getIpVisitCount(String pageName, String ip) {
        if (pageName == null || pageName.trim().isEmpty() || ip == null || ip.trim().isEmpty()) {
            logger.warn("Page name or IP cannot be null or empty");
            return 0;
        }
        
        try {
            String key = getIpVisitKey(pageName, ip);
            Object value = cacheService.get(key);
            if (value != null) {
                return Long.parseLong(value.toString());
            }
            return 0;
        } catch (Exception e) {
            logger.error("Failed to get IP visit count: page={}, ip={}", pageName, ip, e);
            return 0;
        }
    }
}